//
//  TXBaseViewController.m
//  TXKit
//
//  Created by YM on 2017/5/18.
//  Copyright © 2017年 Tincent. All rights reserved.
//

#import "TXBaseViewController.h"
#import <Masonry.h>
#import <BlocksKit+UIKit.h>
#import "MBProgressHUD+TXExtension.h"
#import "TXRefreshHeader.h"
#import "TXRefreshFooter.h"
#import "UIView+TXKit.h"
#import "UIView+TXExtension.h"

@interface TXBaseViewController ()
{
    BOOL worked;
    BOOL worked2;
}
@property(nonatomic, strong) UIView *emptyView;

@end

@implementation TXBaseViewController

#pragma mark - Getter

-(UITableView *)myTableView
{
    if(!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:_tableStyle];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        _myTableView.showsHorizontalScrollIndicator = NO;
        _myTableView.showsVerticalScrollIndicator = NO;
        _myTableView.rowHeight = UITableViewAutomaticDimension;
        _myTableView.estimatedSectionHeaderHeight = 0; //关闭自动估算section header高度
        _myTableView.estimatedSectionFooterHeight = 0; //关闭自动估算section footer高度
        if (@available(iOS 11.0, *)) {
            _myTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _myTableView.tableFooterView = [UIView new]; //隐藏多余的分割线
        [self.view addSubview:_myTableView];
        [_myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
    }
    return _myTableView;
}

-(UIView *)loadingContainerView
{
    if (!_loadingContainerView) {
        CGFloat viewY;
        CGFloat viewH;
        if (self.navigationController.navigationBarHidden) {
            viewY = TX_NAVBAR_HEIGHT;
            viewH = TX_SCREEN_HEIGHT-TX_SAFEAREA_BOTTOM_HEIGHT-viewY;
        } else {
            viewY = 0;
            viewH = TX_SCREEN_HEIGHT-TX_SAFEAREA_BOTTOM_HEIGHT-TX_NAVBAR_HEIGHT-viewY;
        }
        
        //如果在第一层的主页面上,减去tabbar高度
        if (self.navigationController.viewControllers.count == 1) {
            viewH -= TX_TABBAR_HEIGHT;
        }
        
        CGRect frame = CGRectMake(0, viewY, TX_SCREEN_WIDTH, viewH);
        
        _loadingContainerView=[[UIView alloc] initWithFrame:frame];
        
        [self.view addSubview:_loadingContainerView];
    }
    
    return _loadingContainerView;
}

#pragma mark - Setter

-(void)setTableStyle:(UITableViewStyle )tableStyle
{
    _tableStyle = tableStyle;
}

-(void)setHeaderRereshingBlock:(dispatch_block_t)headerRereshingBlock
{
    _headerRereshingBlock = headerRereshingBlock;
    
    if (!self.myTableView.mj_header) {
        
        // 集成下拉刷新
        TX_WS(weakSelf);
        self.myTableView.mj_header = [TXRefreshHeader headerWithRefreshingBlock:^{
            
            weakSelf.headerRereshingBlock();
            
        }];
    }
}

-(void)setHeaderRereshingBlock:(dispatch_block_t)headerRereshingBlock class:(Class )aClass
{
    _headerRereshingBlock = headerRereshingBlock;
    
    if (!self.myTableView.mj_header) {
        
        // 集成下拉刷新
        TX_WS(weakSelf);
        self.myTableView.mj_header = [aClass headerWithRefreshingBlock:^{
            
            weakSelf.headerRereshingBlock();
            
        }];
    }
}

-(void)setFooterRereshingBlock:(dispatch_block_t)footerRereshingBlock
{
    _footerRereshingBlock = footerRereshingBlock;
    
    if (!self.myTableView.mj_footer) {
        
        // 集成上拉加载更多
        TX_WS(weakSelf);
        self.myTableView.mj_footer = [TXRefreshFooter footerWithRefreshingBlock:^{
            
            weakSelf.footerRereshingBlock();
            
        }];
    }
}

-(void)setFooterRereshingBlock:(dispatch_block_t)footerRereshingBlock class:(Class )aClass
{
    _footerRereshingBlock = footerRereshingBlock;
    
    if (!self.myTableView.mj_footer) {
        
        // 集成上拉加载更多
        TX_WS(weakSelf);
        self.myTableView.mj_footer = [aClass footerWithRefreshingBlock:^{
            
            weakSelf.footerRereshingBlock();
            
        }];
    }
}

#pragma mark - Life Circle

-(id)init {
    self=[super init];
    if (self) {
        [self initBaseData];
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self initBaseData];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self initBaseData];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    if (@available(iOS 7.0, *)) {
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    [self setNeedsStatusBarAppearanceUpdate];
}

//返回状态栏颜色
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0, *)) {
        return UIStatusBarStyleLightContent;
    } else {
        return UIStatusBarStyleLightContent;
    }
}

//调整导航条上leftBarButtonItem与屏幕边界的间距
- (void)viewDidLayoutSubviews{
    if ([UIDevice currentDevice].systemVersion.floatValue >= 11.0) {
        UINavigationItem *item = self.navigationItem;
        NSArray *array = item.leftBarButtonItems;
        if (array && array.count) {
            // 注意：这里设置的第一个leftBarButtonItem的customeView不能为空，也就是不要设置UIBarButtonSystemItemFixedSpace这种风格的item
            UIBarButtonItem *btnItem = array[0];
            UIView *view = [[btnItem.customView.superview superview] superview];
            NSArray *arrayConstraint = view.constraints;
            for (NSLayoutConstraint *constant in arrayConstraint) {
                CGFloat space = fabs(constant.constant);
                // 非plus手机为16 plus手机为20
                if (space == 16 || space == 20) {
                    constant.constant = 0;
                }
            }
        }
    }
}

#pragma mark - Help Method

-(void)initBaseData {
    self.tableStyle = UITableViewStylePlain;
}

#pragma mark - Loading

-(void)showLoading {
    
    TX_SHOWLOADING(self.loadingContainerView)
}

-(void)hideLoading {
    
    TX_HIDELOADING(self.loadingContainerView);
    
    if (self.loadingContainerView) {
        [self.loadingContainerView removeFromSuperview];
        self.loadingContainerView = nil;
    }
}

#pragma mark - Empty view

- (id)showEmptyImage:(NSString *)imageName
               title:(NSString *)title
          buttonName:(NSString *)buttonName
           topMargin:(CGFloat )topMargin
              inView:(UIView *)contentView
         buttonBlock:(void (^)(void))onBtnBlock
{
    if (_emptyView == nil) {
        CGFloat width = contentView.width;
        if (width == 0.f) {
            width = TX_SCREEN_WIDTH;
        }
        _emptyView = [[UIView alloc] init];
        _emptyView.frame = CGRectMake(0, 0, width, contentView.height);
        [contentView addSubview:_emptyView];
    }
    
    for (UIView *subview in [_emptyView subviews]) {
        [subview removeFromSuperview];
    }
    
    
    CGFloat contentTop = topMargin;
    CGFloat titleTop = 20;
    CGFloat titleLeft = 30;
    CGFloat btnTop = 12;
    CGFloat btnW = 164;
    CGFloat btnH = 40;
    
    //使用一个container，可以控制所有控件整体的整体位置，或居中、或靠上
    UIView *container = [[UIView alloc] init];
    [_emptyView addSubview:container];
    [container mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(contentTop);
    }];
    
    UIView *lastView = nil;

    //图片
    if (imageName && imageName.length > 0) {
        UIImage *image = [UIImage imageNamed:imageName];
        
        UIImageView *imageview = [[UIImageView alloc] init];
        imageview.image = image;
        [container addSubview:imageview];
        
        [imageview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(0);
            make.size.mas_equalTo(image.size);
            make.centerX.mas_equalTo(0);
        }];
        
        lastView = imageview;
    }
    
    //提示语
    if (title && title.length > 0) {
        UILabel* label = [[UILabel alloc] init];
        label.font = TX_FONT(16);
        label.textColor = TX_COLOR_FROM_RGB(0x999999);
        label.textAlignment = NSTextAlignmentCenter;
        label.text = title;
        label.numberOfLines = 0;
        [container addSubview:label];
        
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            if (lastView) {
                make.top.mas_equalTo(lastView.mas_bottom).mas_equalTo(titleTop);
                make.centerX.mas_equalTo(0);
            } else {
                make.center.mas_equalTo(0);
            }
            make.left.mas_equalTo(titleLeft);
            make.right.mas_equalTo(-titleLeft);
        }];
        
        lastView = label;
    }
    
    //按钮
    if (buttonName && buttonName.length > 0) {
        UIButton* button = [UIButton butonWithTitle:buttonName font:TX_FONT_MEDIUM(15) color:TX_COLOR_FROM_RGB(0xFEFEFE) hlColor:nil disColor:nil bgColor:TX_COLOR_FROM_RGB(0xE3BB81) hlBgColor:TX_COLOR_FROM_RGBA(0xE3BB81, 0.8) disBgColor:TX_COLOR_FROM_RGBA(0xE3BB81, 0.2)];
        [button setLayerCorner:5 borderWidth:0.5 borderColor:TX_COLOR_FROM_RGB(0xE3BB81)];
        
        [container addSubview:button];
        [button bk_addEventHandler:^(id sender) {
            if (onBtnBlock) {
                onBtnBlock();
            }
        } forControlEvents:UIControlEventTouchUpInside];
        
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            if (lastView) {
                make.top.mas_equalTo(lastView.mas_bottom).mas_equalTo(btnTop);
                make.centerX.mas_equalTo(0);
            } else {
                make.center.mas_equalTo(0);
            }
            make.width.mas_equalTo(btnW);
            make.height.mas_equalTo(btnH);
        }];
        
        lastView = button;
    }
    
    //让container的高自适应子控件的内容高度
    [container mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(lastView.mas_bottom);
    }];
    
    return _emptyView;
}

- (id)showEmptyImage:(NSString *)imageName
               title:(NSString *)title
          buttonName:(NSString *)buttonName
              inView:(UIView *)contentView
         buttonBlock:(void (^)(void))onBtnBlock {
    
    CGFloat topMargin = TX_ADAPTED_HEIGHT(115);
    
    return [self showEmptyImage:imageName title:title buttonName:buttonName topMargin:topMargin inView:contentView buttonBlock:onBtnBlock];
}

-(void)hideEmptyView
{
    if (_emptyView) {
        [_emptyView removeFromSuperview];
        _emptyView=nil;
    }
}

#pragma mark - Refreshing

-(void)headerBeginRefreshing {
    NSAssert(_headerRereshingBlock, @"Please call setHeaderRereshingBlock first!");

    [self.myTableView.mj_header beginRefreshing];
}

-(void)headerEndRefreshing {
    [self.myTableView.mj_header endRefreshing];
}

-(void)footerBeginRefreshing {
    NSAssert(_footerRereshingBlock, @"Please call setFooterRereshingBlock first!");

    [self.myTableView.mj_footer beginRefreshing];
}

-(void)footerEndRefreshing {
    [self.myTableView.mj_footer endRefreshing];
}

-(void)setHeaderHidden:(BOOL )hidden {
    self.myTableView.mj_header.hidden = hidden;
}

-(void)setFooterHidden:(BOOL )hidden {
    self.myTableView.mj_footer.hidden = hidden;
}

#pragma mark - UITableViewDataSource & UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    return nil;
}

@end
